import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { getUserDesigns, deleteDesign, Design } from '../services/design';
import CreateDesign from '../components/CreateDesign';
import TextToImageDesign from '../components/TextToImageDesign';

const RoomDesign: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'redesign' | 'textToImage'>('redesign');
  const [processedImage, setProcessedImage] = useState<string | null>(null);
  const [designs, setDesigns] = useState<Design[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { user } = useAuth();
  const history = useHistory();

  useEffect(() => {
    if (user) {
      loadDesigns();
    } else {
      setLoading(false);
    }
  }, [user]);

  const loadDesigns = async () => {
    try {
      setLoading(true);
      const response = await getUserDesigns();
      if (response.success) {
        setDesigns(response.data.designs);
      } else {
        setError(response.message || 'Failed to load designs');
      }
    } catch (err) {
      setError('Failed to load designs');
      console.error('Error loading designs:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleDesignCreated = (imageUrl: string) => {
    setProcessedImage(imageUrl);
    console.log('Design created:', imageUrl);
    loadDesigns(); // Reload designs after creating a new one
  };

  const handleCreditsUpdated = () => {
    console.log('Credits updated');
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center bg-white/80 backdrop-blur-sm p-8 rounded-xl shadow-xl">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">Please log in to view your designs</h2>
          <p className="text-gray-600">You need to be logged in to access design features.</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center">
        <div className="text-center bg-white/80 backdrop-blur-sm p-8 rounded-xl shadow-xl">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 py-5">
      {/* 装饰元素 */}
      <div className="fixed top-0 right-0 w-1/3 h-1/3 bg-gradient-to-br from-blue-300/20 to-purple-300/20 rounded-bl-full -z-10 blur-3xl"></div>
      <div className="fixed bottom-0 left-0 w-1/3 h-1/3 bg-gradient-to-tr from-indigo-300/20 to-pink-300/20 rounded-tr-full -z-10 blur-3xl"></div>
      
      <div className="max-w-[90%] mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-2">
          <h1 className="text-5xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-purple-600 mb-4">Room Design</h1>
          <p className="text-xl text-gray-700">Create stunning room designs with AI</p>
        </div>

        {/* Tab Navigation */}
        <div className="max-w-[95%] mx-auto mb-8 border-b border-gray-200/60">
          <div className="flex -mb-px">
            <button
              onClick={() => setActiveTab('redesign')}
              className={`mr-8 py-4 border-b-2 font-medium text-md transition-all duration-300 ${
                activeTab === 'redesign'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              Room Design
            </button>
            <button
              onClick={() => setActiveTab('textToImage')}
              className={`mr-8 py-4 border-b-2 font-medium text-md transition-all duration-300 ${
                activeTab === 'textToImage'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              Text to Image
            </button>
          </div>
        </div>

        {/* 内容区背景卡片 */}
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-xl p-6 md:p-8 mb-8">
          {/* Room Redesign Tab Content */}
          {activeTab === 'redesign' && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
              className="w-full"
            >
              {/* <div className="text-center mb-8">
                <h2 className="text-2xl font-bold text-gray-900 mb-2">Room Redesign</h2>
                <p className="text-gray-600">Upload your room photo and let AI transform it into your dream space</p>
              </div> */}
              
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
                <CreateDesign 
                  onDesignCreated={handleDesignCreated}
                  onCreditsUpdated={handleCreditsUpdated}
                />
                
                {/* Generated Design Display */}
                <div className="bg-gradient-to-br from-blue-50 via-purple-50 to-white rounded-2xl shadow-xl border-2 border-blue-100 flex flex-col items-center justify-center min-h-[320px] p-6">
                  {processedImage ? (
                    <div className="w-full space-y-4">
                      <img src={processedImage || ''} alt="Generated design" className="w-full rounded-xl shadow-lg" />
                      <button
                        onClick={async () => {
                          try {
                            if (!processedImage) {
                              alert('图片不存在，无法下载');
                              return;
                            }
                            const response = await fetch(processedImage);
                            const blob = await response.blob();
                            const url = window.URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = url;
                            link.download = `room-design-${Date.now()}.jpg`;
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                            window.URL.revokeObjectURL(url);
                          } catch (error) {
                            console.error('下载失败:', error);
                            alert('下载失败，请重试');
                          }
                        }}
                        className="w-full bg-gradient-to-r from-green-500 to-blue-500 text-white py-3 px-4 rounded-xl font-semibold hover:scale-105 hover:shadow-lg transition-all duration-200 flex items-center justify-center gap-2"
                      >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        Download
                      </button>
                    </div>
                  ) : (
                    <div className="text-center text-gray-500">
                      <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                      </svg>
                      <p className="mt-2">Your generated design will appear here</p>
                      <p className="text-sm">Upload an image and click Generate Design to start</p>
                    </div>
                  )}
                </div>
              </div>
            </motion.div>
          )}

          {/* Text to Image Tab Content */}
          {activeTab === 'textToImage' && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
              className="w-full mx-auto"
            >
              {/* <div className="text-center mb-8">
                <h2 className="text-2xl font-bold text-gray-900 mb-2">Text to Image</h2>
                <p className="text-gray-600">Create stunning designs from text descriptions</p>
              </div> */}
              
              <TextToImageDesign 
                onDesignCreated={handleDesignCreated}
                onCreditsUpdated={handleCreditsUpdated}
              />
            </motion.div>
          )}
        </div>
      </div>
    </div>
  );
};

export default RoomDesign;